<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 17-6-13
 * Time: 下午5:35
 */

namespace console\controllers;


use api\modules\chedai\components\OnlineVerify;
use common\components\e_divide\EDivide;
use common\components\huaxiayinhang\Config;
use common\components\huaxiayinhang\Nbrb;
use common\components\sms\Lhwt;
use common\components\tools\AES;
use common\components\tools\Api;
use common\components\tools\Image;
use common\components\tools\Model;
use common\components\tools\OpensslRSA;
use common\components\tools\RSA;
use common\components\tools\Tools;
use common\models\AliCarinfoGetLog;
use common\models\BaiRongValidateForCreditOrder;
use common\models\credit_old_app\SlEloaninfo;
use common\models\credit_public\SlCarModelDycw;
use common\models\credit_public\SlCarModelDycw0;
use common\models\credit_public\SlCarSeriesDycw;
use common\models\Custom;
use common\models\EdiviCommonBackLogs;
use common\models\EdiviCreditOrder;
use common\models\EdiviOrderSendLogs;
use common\models\ImageIndex;
use common\models\MultiMediaUploadQuene;
use common\models\TmpSmsWarningSend;
use console\models\app_tables\Order;
use console\models\app_tables\OrderCert;
use yii\console\Controller;
use yii\db\Exception;
use yii\httpclient\Client;
use common\models\BaiRongValidateLog;
use common\models\CreditOrder;
use common\models\CreditOrderLog;
use yii\base\ErrorException;

class TestController extends Controller
{
    /**
     * php yii test
     * @throws \yii\httpclient\Exception
     */
    public function actionIndex()
    {
        $body = [
            'pub' => [
                'orderNo' => "orderNo",
            ],
        ];
        $body = json_encode($body);
        $client = new \GuzzleHttp\Client([
            'base_uri' => 'http://yii2work.ys.pc',
        ]);
        $resp = $client->request("post", "/e_divide/notify/common-back", [
            'body' => $body,
        ]);
        var_dump($resp->getBody()->getContents());exit;
    }

    /**
     * php yii test/add-edivi-bank-code
     */
    public function actionAddEdiviBankCode()
    {
        $e_order_send_logs = EdiviOrderSendLogs::find()->where(['b_code' => EDivide::B_CODE_CREDIT])->all();
        foreach ($e_order_send_logs as $k => $v){
            $arr = json_decode($v->ed_data, true);
            $bankCode = $arr['data']['pub']['bankCode'];
            $o = $v->ediviCreditOrder;
            $o->bank_code = $bankCode;
            if (!$o->bank_code){
                if ($o->save()){
                    var_dump($o->id);
                }else{
                    var_dump($o->toArray());
                }
            }
        }
    }

    public function actionTestSlave()
    {
        $x = \Yii::$app->db->slave->createCommand("select * from `user` limit 2")->queryAll();
        var_export($x);
        exit;
    }

    /**
     * php yii test/test-sms-send
     */
    public function actionTestSmsSend()
    {
        $sms = new Lhwt();
        $statusCode = $sms->sendSms(['17091551612'], '婚姻证明不符合要求');
        var_dump($statusCode);
    }

    /**
     * php yii test/bairong-copy [once time]
     */
    public function actionBairongCopy()
    {
        /**
         * @var CreditOrderLog[] $vs
         */
        $vs = CreditOrderLog::find()->where(['not', ['big_data_validate_return' => null]])->all();
        foreach ($vs as $k => $v){
            $_re_data = unserialize($v->big_data_validate_return);
            foreach ($_re_data['_back'] as $k1 => $v1){
                $strategy_type = BaiRongValidateLog::STRATEGY_TYPE_DETAIL_LIST;
                if ($k1 == BaiRongValidateLog::STRATEGY_TYPE_DETAIL_LIST){
                    $strategy_type = BaiRongValidateLog::STRATEGY_TYPE_DETAIL_LIST;
                }
                if ($k1 == BaiRongValidateLog::STRATEGY_TYPE_PERSON_RECOGNITION){
                    $strategy_type = BaiRongValidateLog::STRATEGY_TYPE_PERSON_RECOGNITION;
                }
                $check_user = [
                    'id' => $v->creditOrder->idno,
                    'name' => $v->creditOrder->custname,
                    'cell' => $v->creditOrder->mobile,
                ];
                $bair_log = BaiRongValidateLog::findOne([
                    'strategy_type' => $k1,
                    'req_name' => $v->creditOrder->custname,
                    'req_idcard' => $v->creditOrder->idno,
                    'req_mobile' => $v->creditOrder->mobile,
                ]);
                $bair_log->created_at = $v->time;
                if ($bair_log->save()){
                    var_dump($bair_log->toArray());
                }else{
                    var_dump($bair_log->errors);
                }
                if (!in_array($bair_log->resp_code, ['00', '100002', '600000'])){
                    $bair_log->is_old_from_console = 1;
                    $bair_log->api_send_post_data = json_encode($check_user);
                    if ($k1 == BaiRongValidateLog::STRATEGY_TYPE_DETAIL_LIST){
                        $bair_log->resp_swift_number = $v->creditOrder->big_data_validate_detail_shift_number;
                    }
                    if ($k1 == BaiRongValidateLog::STRATEGY_TYPE_PERSON_RECOGNITION){
                        $bair_log->resp_swift_number = $v->creditOrder->big_data_validate_person_recognition_shift_number;
                    }
                    $bair_log->resp_data_for_api_send = json_encode($v1);
                    $bair_log->resp_code = (string)$v1['code'];
                    $bair_log->created_at = $v->time;
                    if ($bair_log->save()){
                        var_dump($bair_log->toArray());
                    }else{
                        var_dump($bair_log->errors);
                    }
                }
                if (!$bair_log){
                    $bair_log = new BaiRongValidateLog();
                    $bair_log->strategy_type = $strategy_type;
                    $bair_log->req_name = $v->creditOrder->custname;
                    $bair_log->req_idcard = $v->creditOrder->idno;
                    $bair_log->req_mobile = $v->creditOrder->mobile;
                    $bair_log->is_old_from_console = 1;
                    $bair_log->api_send_post_data = json_encode($check_user);
                    if ($k1 == BaiRongValidateLog::STRATEGY_TYPE_DETAIL_LIST){
                        $bair_log->resp_swift_number = $v->creditOrder->big_data_validate_detail_shift_number;
                    }
                    if ($k1 == BaiRongValidateLog::STRATEGY_TYPE_PERSON_RECOGNITION){
                        $bair_log->resp_swift_number = $v->creditOrder->big_data_validate_person_recognition_shift_number;
                    }
                    $bair_log->resp_data_for_api_send = json_encode($v1);
                    $bair_log->resp_code = (string)$v1['code'];
                    $bair_log->created_at = $v->time;
                    if ($bair_log->save()){
                        var_dump($bair_log->toArray());
                    }else{
                        var_dump($bair_log->errors);
                    }
                }
                $bind = BaiRongValidateForCreditOrder::findOne(['credit_order_id' => $v->credit_order_id, 'bai_rong_validate_log_id' => $bair_log->id]);
                if (!$bind){
                    $bind = new BaiRongValidateForCreditOrder();
                    $bind->credit_order_id = $v->credit_order_id;
                    $bind->bai_rong_validate_log_id = $bair_log->id;
                    $bind->created_at = $v->time;
                    if (!$bind->save()){
                        throw new ErrorException("保存数据失败".var_export($bind->errors, true));
                    }
                }
            }
        }
    }

    /**
     * php yii test/test-image-water
     */
    public function actionTestImageWater()
    {
        Image::addTextWater('/www/wwwroot/yii2work/web/uploads/images/credit/15522839433759.jpg', '/www/wwwroot/yii2work/web/uploads/images/credit/15522839433759.jpg');
    }

    /**
     * php yii test/test-car-s
     */
    public function actionTestCarS()
    {
        $sql = <<<SQL
SELECT * FROM (
    SELECT 'che300' AS `cs_source`, `cs_car_brand`, `cs_car_text`, `cs_car_type`, `cs_car_price1`, `cs_car_price2`, '' AS `cs_car_url` 
        FROM `sl_car_series` LIMIT 3
    UNION 
    SELECT 'qczj' AS `cs_source`, `cs_car_brand`, `cs_car_text`, `cs_car_type`, `cs_car_price1`, `cs_car_price2`, `cs_car_url`  
        FROM `sl_car_series_qczj` LIMIT 3
    UNION
    (SELECT 'dycw' AS `cs_source`, `brand_name` AS `cs_car_brand`, CONCAT_WS('-', `brand_name`, `car_series_name_show`) AS `cs_car_text`, '' AS `cs_car_type`, '' AS `cs_car_price1`, '' AS `cs_car_price2`, '' AS `cs_car_url` 
        FROM `sl_car_model_dycw` GROUP BY `car_series_id` LIMIT 2)
    ) AS `sl_car_s`
SQL;
        $sql = <<<SQL
SELECT * FROM (
    SELECT 'che300' AS `cs_source`, `cs_car_brand`, `cs_car_text`, `cs_car_type`, `cs_car_price1`, `cs_car_price2`, '' AS `cs_car_url` 
        FROM `sl_car_series` LIMIT 3
    UNION 
    SELECT 'qczj' AS `cs_source`, `cs_car_brand`, `cs_car_text`, `cs_car_type`, `cs_car_price1`, `cs_car_price2`, `cs_car_url`  
        FROM `sl_car_series_qczj` LIMIT 3
    UNION
    (SELECT 'dycw' AS `cs_source`, `brand_name` AS `cs_car_brand`, CONCAT_WS('-', `brand_name`, `car_series_name_show`) AS `cs_car_text`, '' AS `cs_car_type`, '' AS `cs_car_price1`, '' AS `cs_car_price2`, '' AS `cs_car_url` 
        FROM `sl_car_model_dycw` GROUP BY `car_series_id` LIMIT 2)
    ) AS `sl_car_s`
SQL;
        $data = \Yii::$app->db_public->createCommand($sql)->queryAll();
        var_dump($data);
    }

    /**
     * php yii test/move-dycw
     * @throws
     */
    public function actionMoveDycw()
    {
        $x = SlCarModelDycw0::find()->orderBy(['id' => SORT_ASC])->groupBy(['car_series_id'])->all();
        $car_s = new SlCarSeriesDycw();
        $car_m = new SlCarModelDycw();
        $trans = \Yii::$app->db_public->beginTransaction();
        try{
            foreach ($x as $k => $v){
                $s = clone $car_s;
                $s->cs_car_brand = $v->brand_name;
                $s->cs_car_text = $v->brand_name."-".$v->car_series_name_show;
                if (!$s->save()){
                    var_dump(Model::getModelError($s));
                    exit;
                }
                $y = SlCarModelDycw0::find()->where(['car_series_id' => $v->car_series_id])->groupBy(['model_id'])->all();
                foreach ($y as $k1 => $v1) {
                    $m = clone $car_m;
                    $m->dycw_model_id = $v1->model_id;
                    $m->series_id = $s->cs_id;
                    $m->model_name = $v1->model_title_l;
                    $m->liter = $v1->model_displacement;
                    $m->model_year = $v1->model_year;
                    if (!$m->save()){
                        var_dump(Model::getModelError($m));
                        exit;
                    }
                }
            }
            $trans->commit();
        }catch (Exception $e){
            $trans->rollBack();
            throw $e;
        }
    }

    /**
     * php yii test/dycw-set-discharge
     */
    public function actionDycwSetDischarge()
    {
        $x = SlCarModelDycw::find()->all();
        foreach ($x as $k => $v) {
            if (preg_match('/国/', $v->model_name, $ms)){
                $v->discharge_standard = "国产";
                if ($v->save()){
                    var_dump($v->model_id);
                }
            }
            if (preg_match('/进口/', $v->model_name, $ms)){
                $v->discharge_standard = "进口";
                if ($v->save()){
                    var_dump($v->model_id);
                }
            }
        }
    }

    /**
     * php yii test/ali10
     */
    public function actionAli10()
    {
        $x = AliCarinfoGetLog::find()->where(['type' => AliCarinfoGetLog::TYPE_LSFPZW])->all();
        var_dump(count($x));
        foreach ($x as $k => $v){
            $body = $v->resp_body;
            $arr = json_decode($body, true);
            if (!isset($arr['invoiceResult'])){
                var_dump($arr);
                continue;
            }
            if (!is_array($arr['invoiceResult'])){
                $arr['invoiceResult'] = json_decode($arr['invoiceResult'], true, 512);
            }
            $v->RtnCode = isset($arr['RtnCode'])?$arr['RtnCode']:null;
            $v->resultCode = isset($arr['resultCode'])?$arr['resultCode']:null;
            $v->invoicefalseCode = isset($arr['invoicefalseCode'])?$arr['invoicefalseCode']:null;
            $v->resultMsg = isset($arr['resultMsg'])?$arr['resultMsg']:null;
            $v->invoiceName = isset($arr['invoiceName'])?$arr['invoiceName']:null;
            $v->invoiceResult = json_encode($arr['invoiceResult']);
            $v->isFree = isset($arr['isFree'])?$arr['isFree']:null;
            $v->invoiceDataCode = $v->fpdm = isset($arr['invoiceResult']['invoiceDataCode'])?$arr['invoiceResult']['invoiceDataCode']:null;
            $v->invoice_number = $v->fphm = isset($arr['invoiceResult']['invoiceNumber'])?$arr['invoiceResult']['invoiceNumber']:null;
            $v->billingTime = $v->kprq = $v->invoice_created_date = isset($arr['invoiceResult']['billingTime'])?$arr['invoiceResult']['billingTime']:null;
            $v->checkCode = isset($arr['invoiceResult']['checkCode'])?$arr['invoiceResult']['checkCode']:null;
            $v->vehicle_type = $v->car_type = isset($arr['invoiceResult']['vehicleType'])?$arr['invoiceResult']['vehicleType']:null; // 车辆类型
            $v->engine_num = $v->engine_number = isset($arr['invoiceResult']['engineNumber'])?$arr['invoiceResult']['engineNumber']:null; // 发动机号码
//        $v->plate_num = isset($arr['invoiceResult']['plateNo'])?$arr['invoiceResult']['plateNo']:null; // 老的车牌号
            $v->invoice_created_date = $v->kprq = $v->billingTime; // 发票开票日期
            $v->owner = isset($arr['invoiceResult']['purchaserName'])?$arr['invoiceResult']['purchaserName']:null;
            $v->vin = isset($arr['invoiceResult']['frameNumbr'])?$arr['invoiceResult']['frameNumbr']:null;
            $v->request_djzs_str= isset($arr['invoiceResult']['registNo'])?$arr['invoiceResult']['registNo']:null;
            $v->jshe= isset($arr['invoiceResult']['totalTaxSum'])?$arr['invoiceResult']['totalTaxSum']:null;
            $v->model= isset($arr['invoiceResult']['brandType'])?$arr['invoiceResult']['brandType']:null;
            if (isset($arr['invoiceResult']['salesName'])){
                $v->xhdwmc = $arr['invoiceResult']['salesName'];
            }
            if (isset($arr['invoiceResult']['secondHandMarket'])){
                $v->xhdwmc = $arr['invoiceResult']['secondHandMarket'];
            }
            if (isset($arr['invoiceResult']['secondHandMarketNo'])){
                $v->xhdwmc_no = $arr['invoiceResult']['secondHandMarketNo'];
            }elseif (isset($arr['invoiceResult']['salesTaxpayerNum'])){
                $v->xhdwmc_no = $arr['invoiceResult']['salesTaxpayerNum'];
            }
            if (!$v->save()){
                var_dump(Model::getModelError($v));
                exit;
            }else{
                var_dump($v->id);
            }
        }
    }

    /**
     * php yii test/jzg-update-price
     */
    public function actionJzgUpdatePrice()
    {
        $data_arr = [
            '!ysjr0000000068049' => "WBA1A1106CE599755",
            '!ysjr0000000068078' => "LJDMAA226G0626714",
            '!ysjr0000000068088' => "WDDHF4JB5AA244592",
            '!ysjr0000000068107' => "1C4NJDAB0CD569423",
            '!ysjr0000000068118' => "LFMAPE2C9A0211765",
            '!ysjr0000000068119' => "LFV3A28K1A3058770",
            '!ysjr0000000068122' => "LSGUA84B3DE030261",
            '!ysjr0000000068131' => "LDCC13L32B1570818",
            '!ysjr0000000068142' => "LBECFAHB1EZ084210",
            '!ysjr0000000068149' => "LBVPS3106BSD39684",
            '!ysjr0000000068159' => "LSGAR5AL5HH245586",
            '!ysjr0000000068174' => "LSVUB25NXA2869994",
            '!ysjr0000000068177' => "LSVCM2BM9GN153919",
            '!ysjr5000000068140' => "LHGGE6831D2002275",
            '!ysjr0000000068205' => "LE4GG8BB7DL242371",
            '!ysjr0000000068208' => "5TFAY5F11EX378627",
            '!ysjr0000000068216' => "LHGCP1688A2030659",
            '!ysjr0000000068218' => "WDDSJ4DB4HN409700",
            '!ysjr0000000068228' => "LSGKE54A8JW183838",
            '!ysjr0000000068250' => "LVHRM2838D5011366",
            '!ysjr0000000068258' => "LFV2A21K8C4186667",
            '!ysjr0000000068265' => "1FTEX1E61AFC44243",
            '!ysjr0000000068296' => "LE4ZF4JB6HL039631",
            '!ysjr0000000068319' => "LSVAA2BR9DN045887",
            '!ysjr0000000068329' => "LBEMDAEC7EZ404427",
            '!ysjr0000000068337' => "LSVGY2182H2117454",
            '!ysjr0000000068364' => "LFV4A24F093049888",
            '!ysjr0000000068376' => "LFV3A28K6G3503092",
            '!ysjr0000000068396' => "LVHFB2674D6023622",
            '!ysjr0000000068413' => "LSGUD84X4EE050913",
            '!ysjr0000000068414' => "LVSFCAAE2EF722580",
            '!ysjr0000000068418' => "LBV5S1109ESH71296",
            '!ysjr0000000068478' => "3C4PFABB9ET168005",
            '!ysjr0000000068479' => "LFBGE3069DJD62746",
            '!ysjr0000000068481' => "LSYYDBCC2DC086943",
            '!ysjr0000000068482' => "LHGCP1681B8007853",
            '!ysjr0000000068483' => "LSGGA53F8DH000123",
            '!ysjr0000000068495' => "LFV3A24GXE3060248",
            '!ysjr0000000068521' => "LSGJA52U6AS088397",
            '!ysjr0000000068530' => "LSVCD2A43CN048062",
            '!ysjr0000000068532' => "LSGJA52U2BH262156",
            '!ysjr0000000068539' => "LHGGE6731C2008349",
            '!ysjr0000000068542' => "LFV3A28K4B3056917",
            '!ysjr0000000068549' => "LN86GCAE9HB101662",
            '!ysjr0000000068561' => "LVHFA1637B5035793",
            '!ysjr0000000068563' => "LSGJA52H5EH290492",
            '!ysjr0000000068566' => "LGWEF6A51FH025685",
            '!ysjr0000000068576' => "LFV3A23C5C3016928",
            '!ysjr0000000068582' => "LSGPC52HXFF114359",
            '!ysjr0000000068583' => "LJXCMCCB4FT121641",
            '!ysjr0000000068602' => "LJDKAA248B0023152",
            '!ysjr0000000068609' => "LL66HBB07HB143406",
        ];
        foreach ($data_arr as $k => $v) {
            $r = Api::request('/jzg/default/order-infos', [
                'orderNum' => $k,
            ]);
            var_dump($r);
        }
    }

    /**
     * php yii test/edivi-back-jobs
     */
    public function actionEdiviBackJobs()
    {
        exit(-1);
//        $all = EdiviCommonBackLogs::find()->where(['>', 'edivi_credit_order_id', 73])->andWhere(['!=', 'trans_type', 4])->all();
        $all = EdiviCommonBackLogs::find()->all();
        foreach ($all as $k => $v) {
            $edivi_c = $v->ediviCreditOrder;
            $eloaninfo = SlEloaninfo::findOne(['e_o_number' => $edivi_c->order_no]);
            if (!$eloaninfo){
                $eloaninfo = new SlEloaninfo();
                $eloaninfo->e_o_number = $edivi_c->order_no;
            }
            $eloaninfo->e_orderNo = $edivi_c->estage_order_no;
            $eloaninfo->e_status = $v->trans_type;
            if ($edivi_c->lastCreditSendLog){
                $eloaninfo->e_add_time = $edivi_c->lastCreditSendLog->created_at;
            }
            if ($v->trans_type == EdiviCommonBackLogs::TRANS_TYPE_3){
                $eloaninfo->e_refuse_time = $edivi_c->resumeBackLog->created_at;
            }
            if ($v->opinion){
                $eloaninfo->e_remark = $v->opinion;
            }
            if (!$eloaninfo->save()){
                EDivide::notifyBack(31, 31, Model::getModelError($eloaninfo), Model::getModelError($eloaninfo));
            }
            var_dump($v->id);
        }
    }

    /**
     * php yii test/send-warning-sms
     * @throws
     */
    public function actionSendWarningSms()
    {
//        $sql = <<<SQL
//select o_number,cm_vip_name,cm_tel,mp_adtime from sl_order left join sl_car_man on o_number = cm_number left join sl_make_pledge on o_number = mp_number where o_status not in('作废','退单','已结清','面签退单') and cm_type = '购车人' and cm_tel !='' and  mp_adtime < 20190719 and mp_adtime> 0 group by cm_tel
//SQL;
//        $data = \Yii::$app->db_old_app->createCommand($sql)->queryAll();
//        $reg = '/^(1(([35789][0-9])|(47)))\d{8}$/';
//        $tm = new TmpSmsWarningSend();
//        foreach ($data as $k => $v){
//            $mobile = trim($v['cm_tel']);
//            if (preg_match($reg, $mobile)){
//                $t = clone $tm;
//                $t->mobile = $mobile;
//                $t->status = 0;
//                if (!$t->save()){
//                    var_dump($t->errors);
//                    exit;
//                }else{
//                    var_dump($t->mobile);
//                }
//            }
//        }
        exit;
        $sms = new Lhwt();
        $tms = TmpSmsWarningSend::find()->where(['status' => 0])->all();
        foreach ($tms as $k => $v) {
            $r = $sms->sendSms([$v->mobile], "尊敬的客户：您好！最近有不法分子假冒本公司名义进行诈骗活动，在此提醒您明辨真伪，谨防受骗上当。如有收到疑似诈骗电话，请及时联系您的车贷业务负责人。如已形成经济损失，请及时向公安机关报案。—易商新程（杭州）有限公司");
            if ($r == 0 || $r == '0'){
                $v->send_at = time();
                $v->status = 1;
                if($v->save()){
                    var_dump($v->mobile);
                }else{
                    var_dump($v->errors);
                    exit;
                }
            }else{
                var_dump($r);
                exit;
            }
        }
    }

    /**
     * php yii test/test2
     * @throws
     */
    public function actionTest2()
    {
        $url = "http://api.aidianwei.com:8990/ds/verify.do";
        $enkey = "JQ7WhA8MwwDUcEuD";
        $channelId = "2104";
        $iv = "              ds";
        $pre_params = [
            'productCode' => "8204",
            'cid' => "420321197712050128",
            'name' => "冯海珍",
            'subChannelName' => "易商新程（杭州）有限公司",
            'channelOrderId' => "1568688469291",
        ];
        $pre_json = json_encode($pre_params, JSON_UNESCAPED_UNICODE);
        $pre_data = openssl_encrypt($pre_json, 'AES-128-CBC', $enkey, OPENSSL_RAW_DATA, $iv);
        $pre_base64 = base64_encode($pre_data);
        $pre_base64_hex = bin2hex($pre_base64);
        $post_params = [
            'channelId' => $channelId,
            'signData' => $pre_base64_hex,
        ];
        $post_json = json_encode($post_params, JSON_UNESCAPED_UNICODE);
        $client = new \GuzzleHttp\Client();
        $resp = $client->request('POST', $url, [
            'body' => $post_json,
            'headers' => [
                'Content-Type' => 'application/json',
            ],
        ]);
        var_dump($resp->getBody()->getContents());
    }
}